#!/usr/bin/env python
# coding=UTF-8
import random
import logging
import json
import time
import urllib
import datetime

import config

from nsq.http import nsqd
import copy

class MaJiangCheck():
    def __init__(self):
        self._res = []
    
    def all_combination(self, all_card, card):
        c1 = card + 1
        c2 = card + 2
        res = []
        if all_card.count(card) >= 2:
            res.append([card, card])
        if card < 400:
            if c1 in all_card and c2 in all_card:
                res.append([c1, c2])
        return res
    
    def card_group(self, all_card, pre=''):
        card_list = self.trans_card(all_card)
        if not card_list:
            return self._res
        c = card_list.pop(0)
        all_group = self.all_combination(card_list, c)
        if not all_group:
            return self.card_group(card_list, pre)
        for group in all_group:
            tmp = pre
            card_copy = copy.deepcopy(card_list)
            g1 = group[0]
            g2 = group[1]
            card_copy.remove(g1)
            card_copy.remove(g2)
            tmp += "%s,%s,%s_" % (c, g1, g2)
            self._res.append(tmp)
            self.card_group(card_copy, tmp)
        return self._res
        
    def card_group_merge(self, all_card):
        card_list = self.trans_card(all_card)
        tmp_result = []
        for group in self._res:
            if group.endswith("_"):
                group = group[:-1]
            rows = group.split("_")
            if len(rows) > len(tmp_result):
                tmp_result = rows
        res = []
        for row in tmp_result:
            seq = []
            for x in row.split(","):
                if int(x) in card_list:
                    card_list.remove(int(x))
                seq.append(int(x))
            res.append(seq)
        self._res = []
        return res, card_list

    def trans_card(self, all_card):
        return sorted([int(x) for x in all_card])
    
    def get_jiang(self, card, joker_list=[]):
        r = []
        for k in set(card):
            if card.count(k) >= 2 or joker_list:
                r.append(k)
        r.sort()
        return r
    
    def count_group(self, all_card, jiang):
        n = 0
        card_list = self.trans_card(all_card)
        if card_list.count(jiang) < 2:
            return 0, []
        else:
            card_list.remove(jiang)
            card_list.remove(jiang)
        n += 1
        card_list.sort()
        self.card_group(card_list, '')
        seq, left_card = self.card_group_merge(card_list)
        n += len(seq)
        return n, left_card
    
    def check_win(self, n, current_card, card=''):
        if card:
            current_card.append(card)
        jiang_list = self.get_jiang(current_card)
        for jiang in jiang_list:
            allcard = self.trans_card(current_card)
            group_n, left_card = self.count_group(allcard, jiang)
            if not left_card and group_n + n >= 5:
                return True
        return False

    
def json_encode(data):
    return json.dumps(data, separators=(',', ':'))

def nsq_pub(message, topic='response'):
    try:
        nsq_client = nsqd.Client("http://%s/" % config.NSQ_HTTP)
        if isinstance(message, dict):
            message = json_encode(message)
        logging.info(u"推送消息:%s" % message)
        nsq_client.pub(topic, message)
        return True
    except:
        logging.error("nsq send error", exc_info=True)
        return False